<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\web\BadRequestHttpException;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $imageFile;

    public function rules()
    {
        return [
            ['imageFile', 'file', 'skipOnEmpty' => true, 'extensions' => 'png,jpg,jpeg,gif', 'checkExtensionByMimeType' => false, 'maxSize' => 1024000],
        ];
    }



    public function upload()
    {
        if ($this->validate()) {
            $base_path ='uploads/'. date('Y-m-d' , time()) . '/';
            $saveName = $base_path . time() . '_' . mt_rand() . '.' . $this->imageFile->extension;
            if(!is_dir($base_path)) {
                mkdir($base_path , 0777);
            } 
            if($this->imageFile->saveAs($saveName)){
                $this->imageFile = $saveName;
                return true;
            }else{
                return false;
            }
        }else{
            $errors = $this->firstErrors;
            $str = '';
            foreach($errors as $e){
               $str .= $e; 
            }
            throw new BadRequestHttpException($str);
        }
    }
}
